package com.huiyin;

import android.app.Notification;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.support.multidex.MultiDex;
import android.text.TextUtils;

import com.baidu.android.pushservice.CustomPushNotificationBuilder;
import com.baidu.android.pushservice.PushManager;
import com.huiyin.bean.LoginInfo;
import com.huiyin.bean.ShopItem;
import com.huiyin.db.DBHelper;
import com.huiyin.db.SQLOpearteImpl;
import com.huiyin.utils.LocationUtil;
import com.huiyin.utils.NetworkUtils;
import com.huiyin.utils.PreferenceUtil;
import com.huiyin.utils.SettingPreferenceUtil;
import com.huiyin.utils.YsfUtil;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.orhanobut.logger.Logger;
import com.vCamera.VCameraApplication;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;

public class AppContext extends VCameraApplication {

	private static final String TAG = "AppContext";
	private static AppContext instance;
	public static UserInfo mUserInfo;
	public static String userId; // 用户id
	public static boolean isFirstCopy = true;
	public static String MAIN_TASK;
	public static String FIRST_PAGE = "0";
	public static String CLASSIC = "1";
	public static String SHOPCAR = "2";
//	public static String HOUSEKEEPER = "3";
	//add by zhyao @2015/8/27 添加DISCUZ智慧社区，修改LEHU值为５
	//delete by zhyao @2016/5/15 删除智慧社区
//	public static String DISCUZ = "3";
//	public static String MOMENTS = "4";
//	public static String LEHU = "5";
	public static String MOMENTS = "3";
	public static String LEHU = "4";
	public static boolean hasNewScanRecord = true;
	public static String orderId;// 用户的订单号
	public static String number;// 用户的订单编号
	public static String price;// 用户的订单金额
	public static String resultType;// 支付结果类型
	public static int payType;// 支付方式，1.支付宝 2.银联 3.微信4.服务卡
    public static String curTime;//系统当前时间
    public static String userNum;//水电煤用户编号

	// 用于今日头条显示页号的索引,没办法只能往这加
	public int newsTodayPage = 0;

	// 未登录情况下添加到购物车的商品列表数据
	public static ArrayList<ShopItem> shopCarLists;

	// 百度云推送相关
	public String userIdBai;
	public String channelIdBai;

	// 便民服务卡号
	public static String cardNumber;
	public static String token;


	private static DBHelper dbHelper;
	private static SQLiteDatabase db;

	public String nearbyId;
	
	// add by zhyao @2015/8/11 添加区域ID
	public int regionId = -1;
	
	public int getRegionId() {
		// 如果区域为空，则默认为南京市regionId
		if(regionId == -1) {
			SQLOpearteImpl soi = new SQLOpearteImpl(getApplicationContext());
			int cityid = soi.checkIdByName("南京市");
			soi.CloseDB();
			return cityid;
		}
		return regionId;
	}
	
	public void setRegionId(int regionId) {
		this.regionId = regionId;
	}
	
	public String getNearbyId() {
		nearbyId = getResources().getString(R.string.config_number);
		return nearbyId;
	}

	public static AppContext getInstance() {
		if (instance == null) {
			instance = new AppContext();
		}
		return instance;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		instance = this;
		// Thread.setDefaultUncaughtExceptionHandler(AppException.getInstance());
		dbHelper = DBHelper.getInstance(this);
		db = dbHelper.getWritableDatabase();

		initData();
		initImageLoader(getApplicationContext());
		initYsf();
		SharedPreferences mPreferences = getSharedPreferences("bind", Context.MODE_PRIVATE);
		channelIdBai = mPreferences.getString("channelIdBai", "");
		userIdBai = mPreferences.getString("userIdBai", "");
		
		startLocation();

        Logger.init("huiyin")               // default PRETTYLOGGER or use just init()
               .setMethodCount(3);          // default 2
	}

    public void setBaiduNotification(boolean needSound) {
        CustomPushNotificationBuilder cBuilder = new CustomPushNotificationBuilder(this, R.layout.bpush_media_list_item,
                R.id.bpush_media_list_img, R.id.bpush_media_list_title, R.id.bpush_media_list_from_text);
        cBuilder.setNotificationFlags(Notification.FLAG_AUTO_CANCEL);
        cBuilder.setNotificationDefaults(needSound?Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE:Notification.DEFAULT_VIBRATE);
        cBuilder.setStatusbarIcon(R.drawable.ic_launcher);
        cBuilder.setLayoutDrawable(2);
        PushManager.setNotificationBuilder(this, 2, cBuilder);
    }

    public static SQLiteDatabase getDB() {
		return db;
	}

	public static void openDB() {
		if (!db.isOpen()) {
			db = dbHelper.getWritableDatabase();
		}
	}

	public static void closeDB() {
		dbHelper.close();
	}

	private void initData() {
		MAIN_TASK = "";
		mUserInfo = null;
		userId = null; // 用户id
		hasNewScanRecord = true;
		
		//初始化缓存的userInfo信息
		UserInfo userInfo = UserInfo.loadUserInfo(this);
		if(null != userInfo){
			mUserInfo = userInfo;
			userId = userInfo.userId;
		}
	}

	/**
	 * 初始化图片加载器
	 *
	 * @param context
	 */
	public void initImageLoader(Context context) {
		File cacheDir = StorageUtils.getOwnCacheDirectory(getApplicationContext(), "huiyinlehu/cache/ImageCache");
		// DisplayImageOptions mOptions = new
		// DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisc(true)
		// .showStubImage(R.drawable.image_default_rectangle).showImageForEmptyUri(R.drawable.image_default_rectangle)
		// .showImageOnFail(R.drawable.image_default_rectangle).build();
		// ImageLoaderConfiguration config = new
		// ImageLoaderConfiguration.Builder(getApplicationContext())
		// .denyCacheImageMultipleSizesInMemory()
		// .threadPoolSize(5)
		// // 线程池内加载的数量
		// .threadPriority(Thread.NORM_PRIORITY -
		// 2).denyCacheImageMultipleSizesInMemory()
		// .memoryCache(new LruMemoryCache(2 * 1024 * 1024)).memoryCacheSize(2 *
		// 1024 * 1024)
		// .discCacheSize(50 * 1024 *
		// 1024).denyCacheImageMultipleSizesInMemory()
		// .discCacheFileNameGenerator(new
		// Md5FileNameGenerator()).tasksProcessingOrder(QueueProcessingType.LIFO)
		// .discCacheFileCount(100).defaultDisplayImageOptions(mOptions).discCache(new
		// UnlimitedDiscCache(cacheDir))
		// .imageDownloader(new BaseImageDownloader(context, 5 * 1000, 30 *
		// 1000)).build();
		// ImageLoader.getInstance().init(config);
		DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(R.drawable.image_default_rectangle)
				.showImageForEmptyUri(R.drawable.image_default_rectangle).showImageOnFail(R.drawable.image_default_rectangle)
				.imageScaleType(ImageScaleType.IN_SAMPLE_INT).cacheInMemory(true).cacheOnDisc(true)
				.bitmapConfig(Bitmap.Config.RGB_565).build();
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context).threadPriority(Thread.NORM_PRIORITY)
				.denyCacheImageMultipleSizesInMemory().defaultDisplayImageOptions(options)
				.memoryCache(new LruMemoryCache(5 * 1024 * 1024)).discCacheFileNameGenerator(new Md5FileNameGenerator())
				.tasksProcessingOrder(QueueProcessingType.LIFO).discCache(new UnlimitedDiscCache(cacheDir)).build();
		ImageLoader.getInstance().init(config);
	}

	public static void saveLoginInfo(Context mContext, LoginInfo mLoginInfo) {

		SharedPreferences mPreferences = mContext.getSharedPreferences("LoginInfo", Context.MODE_PRIVATE);

		Editor mEditor = mPreferences.edit();
		mEditor.putString("userName", mLoginInfo.userName);
		mEditor.putString("psw", mLoginInfo.psw);
		mEditor.putBoolean("isChecked", mLoginInfo.isChecked);

		mEditor.commit();

	}

	public static LoginInfo getLoginInfo(Context mContext) {

		SharedPreferences mPreferences = mContext.getSharedPreferences("LoginInfo", Context.MODE_PRIVATE);

		LoginInfo loginInfo = new LoginInfo();
		loginInfo.userName = mPreferences.getString("userName", "");
		loginInfo.psw = mPreferences.getString("psw", "");
		loginInfo.isChecked = mPreferences.getBoolean("isChecked", false);

		return loginInfo;
	}

	/**
	 * 保存对象
	 *
	 * @param ser
	 * @param file
	 * @throws IOException
	 */
	public boolean saveObject(Serializable ser, String file) {
		FileOutputStream fos = null;
		ObjectOutputStream oos = null;
		try {
			fos = openFileOutput(file, MODE_PRIVATE);
			oos = new ObjectOutputStream(fos);
			oos.writeObject(ser);
			oos.flush();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				oos.close();
			} catch (Exception e) {
			}
			try {
				fos.close();
			} catch (Exception e) {
			}
		}
	}

	/**
	 * 读取对象
	 * 
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public Serializable readObject(String file) {
		if (!isExistDataCache(file))
			return null;
		FileInputStream fis = null;
		ObjectInputStream ois = null;
		try {
			fis = openFileInput(file);
			ois = new ObjectInputStream(fis);
			return (Serializable) ois.readObject();
		} catch (FileNotFoundException e) {
		} catch (Exception e) {
			e.printStackTrace();
			// 反序列化失败 - 删除缓存文件
			if (e instanceof InvalidClassException) {
				File data = getFileStreamPath(file);
				data.delete();
			}
		} finally {
			try {
				ois.close();
			} catch (Exception e) {
			}
			try {
				fis.close();
			} catch (Exception e) {
			}
		}
		return null;
	}

	/**
	 * 判断缓存是否存在
	 * 
	 * @param cachefile
	 * @return
	 */
	private boolean isExistDataCache(String cachefile) {
		boolean exist = false;
		File data = getFileStreamPath(cachefile);
		if (data.exists())
			exist = true;
		return exist;
	}

	public void saveCacheAppindexFirstData(String data) {
		String cacheName = "cache_appindexfirst_data";
		saveObject(data, cacheName);
	}

	public String getCacheAppindexFirstData() {
		String cacheName = "cache_appindexfirst_data";
		return (String) readObject(cacheName);
	}

	public void saveCacheAppIndexPolyData(String data) {
		String cacheName = "cache_appindexpoly_data";
		saveObject(data, cacheName);
	}

	public String getCacheAppIndexPolyFirstData() {
		String cacheName = "cache_appindexpoly_data";
		return (String) readObject(cacheName);
	}

	public void saveCacheClassic(String data) {
		String cacheName = "cache_appclassic_data";
		saveObject(data, cacheName);
	}

	public String getCacheClassic() {
		String cacheName = "cache_appclassic_data";
		return (String) readObject(cacheName);
	}


	public void initYsf() {
		YsfUtil.init(instance);
	}

    public SettingPreferenceUtil.SettingItem getSettingSharePreference(){
        return SettingPreferenceUtil.getInstance(getApplicationContext()).getSettingItem();
    }
    public void setSettingSharePreference(SettingPreferenceUtil.SettingItem item){
         SettingPreferenceUtil.getInstance(getApplicationContext()).setSettingItem(item);
    }

    public boolean isWifi(){
      return NetworkUtils.isWifi(getApplicationContext());
    }

    /**
     * 获取购物车ID
     * @return
     */
	public static String getShopcardId() {
		
//		//购物车ID
//		String shopcardId = PreferenceUtil.getInstance(instance).getString(PreferenceUtil.PRFERENCE_SHOPCARD_ID);
//		if(TextUtils.isEmpty(shopcardId)){
//			return "-1";
//		}
//		return shopcardId;
		//modify by zhyao @2016/7/14 目前加入购物车必须登录，废弃本地购物车，本地的购物车id永远为-1
		return "-1";
	}

	/**
	 * 购物车ID叠加
	 * @param tempId
	 */
	public static void appendShopcard(String tempId) {
		
		//购物车ID为空则直接返回
		if(TextUtils.isEmpty(tempId)){
			return;
		}
		
		String shopcardId = PreferenceUtil.getInstance(instance).getString(PreferenceUtil.PRFERENCE_SHOPCARD_ID);
		if(TextUtils.isEmpty(shopcardId)){
			
			//第一次存购物车ID
			shopcardId = tempId;
		}else{
			
			//购物车ID叠加
			String[] ids = shopcardId.split(",");
			for(int i=0; i<ids.length; i++){
				if(ids[i].equals(tempId)){
					
					//已经存在购物车ID，则直接返回
					return;
				}
			}
			
			//购物车ID叠加
			shopcardId = shopcardId + "," + tempId;
		}
		
		//保存最新的购物车id
		PreferenceUtil.getInstance(instance).putString(PreferenceUtil.PRFERENCE_SHOPCARD_ID, shopcardId);
	}

	/**
	 * 删除购物车ID
	 */
	public static void deleteShopcardId() {
		PreferenceUtil.getInstance(instance).putString(PreferenceUtil.PRFERENCE_SHOPCARD_ID, "");
	}

	
	/**
     * 获取图片服务器地址
     * @return
     */
	public static String getImageServer() {
		
		//图片服务器地址
		String imageUrl = PreferenceUtil.getInstance(instance).getString(PreferenceUtil.PRFERENCE_IMAGESERVER);
		return imageUrl;
	}
	
	/**
     * 设置图片服务器地址
     * @return
     */
	public static void setImageServer(String url) {
		
		//图片服务器地址
		if(!TextUtils.isEmpty(url)){
			PreferenceUtil.getInstance(instance).putString(PreferenceUtil.PRFERENCE_IMAGESERVER, url);
		}
	}
	
	public void startLocation() {
		LocationUtil locationUtil = new LocationUtil();
		locationUtil.startLocation(instance);
	}

	@Override
	protected void attachBaseContext(Context base) {
		super.attachBaseContext(base);
		MultiDex.install(this);
	}
}